package net.toocruel.iqismart.web.controller.admin;

import net.toocruel.iqismart.dao.AreaRepository;
import net.toocruel.iqismart.dao.condition.UserCondition;
import net.toocruel.iqismart.entity.common.Area;
import net.toocruel.iqismart.entity.constants.Gender;
import net.toocruel.iqismart.entity.constants.UserStatus;
import net.toocruel.iqismart.entity.rbac.Role;
import net.toocruel.iqismart.entity.rbac.User;
import net.toocruel.iqismart.service.RoleService;
import net.toocruel.iqismart.service.UserService;
import net.toocruel.iqismart.service.exception.UserRepeatException;
import net.toocruel.iqismart.utils.FileUploadUtils;
import net.toocruel.iqismart.web.controller.base.AbstractBaseController;
import net.toocruel.iqismart.service.dto.SessionMessage;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description
 * @Auther sty
 * @createTime 2018/4/28 上午11:55
 */
@Controller
@RequestMapping("admin/user")
public class AdminUserController extends AbstractBaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private AreaRepository areaRepository;

    @Autowired
    private FileUploadUtils fileUploadUtils;

    @RequestMapping("")
    public String index(HttpServletRequest request,
                        HttpServletResponse response,
                        @RequestParam(defaultValue = "14") int size,
                        @RequestParam(defaultValue = "1") int page,
                        @RequestParam(defaultValue = "id") String sortBy,
                        @RequestParam(defaultValue = "desc") String sortOrder,
                        UserCondition condition){

        Page<User> users = userService.query(condition,new PageRequest(page-1, size,new Sort(Sort.Direction.fromString(sortOrder),sortBy)));
        request.setAttribute("users",users);
        request.setAttribute("UserStatus",UserStatus.values());
        request.setAttribute("condition",condition);
        request.setAttribute("page",page);
        request.setAttribute("size",size);
        return  "admin/user/index";
    }

    @GetMapping("create")
    public String create(HttpServletRequest request,User user){
        return  "admin/user/create";
    }

    @PostMapping("create")
    public String doCreate(@Valid  User user,BindingResult bindingResult,HttpServletRequest request) throws BindException {
        //此处 声明了BindingResult bindingResult参数 则验证失败时不会抛出4xx错误 需要自己处理
        if(!bindingResult.hasErrors()){
            try {
                userService.create(user);
                return  "redirect:/admin/user";
            } catch (UserRepeatException e) {
                e.printStackTrace();
                request.setAttribute("error",e);
            }
        }

        return  "admin/user/create";

    }

    @GetMapping("{id}")
    public String edit(@PathVariable("id") Long id, User user,HttpServletRequest request, HttpSession session, RedirectAttributes redirectAttributes) {
        BeanUtils.copyProperties(userService.findById(id),user);
        return  "/admin/user/edit";

    }

    @PutMapping("{id}")
    public String doEdit(@PathVariable("id") Long id,
                         @Valid  User user,
                         BindingResult bindingResult,
                         @RequestParam("avatarFile") MultipartFile avatarFile,
                         HttpServletRequest request,
                         HttpSession session,
                         RedirectAttributes redirectAttributes
                         ) {
        List<FieldError> errors = new ArrayList<>();
        bindingResult.getFieldErrors().stream().forEach(fieldError -> {
            if(!fieldError.getField().equals("password")){
                errors.add(fieldError);
            }
        });
        if(errors.isEmpty()){

            if (!avatarFile.isEmpty()) {
                try {
                    fileUploadUtils.uploadAvatar(user.getId(),avatarFile.getInputStream());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            try {
                userService.update(user);
                redirectAttributes.addFlashAttribute("message",new SessionMessage("修改用户成功"));
                refreshCurrentUser();
                return  "redirect:/admin/user";
            } catch (UserRepeatException e) {
                e.printStackTrace();
                request.setAttribute("error",e);
            }
        }

        return  "redirect:/admin/user/"+id;

    }



    @PostMapping("destroy")
    public String doDestroy(Long[] id, HttpSession session,RedirectAttributes redirectAttributes) {
        int i = userService.deleteMany(id);
        redirectAttributes.addFlashAttribute("message",new SessionMessage("成功删除了"+i+"个用户"));
        return  "redirect:/admin/user";

    }

    @PostMapping("verify")
    public String doVerify(Long[] id, HttpSession session,RedirectAttributes redirectAttributes) {
        int i = userService.verifyMany(id);
        redirectAttributes.addFlashAttribute("message",new SessionMessage("成功审核了"+i+"个用户"));
        return  "redirect:/admin/user";

    }





//
//    @ModelAttribute("userInfo")
//    public User createUserInfo() {
//        return new User();
//    }

    @ModelAttribute("roles")
    public List<Role> createRoles() {
        return roleService.findAll();
    }

    @ModelAttribute("UserStatus")
    public UserStatus createUserStatus() {
        return UserStatus.REVIEW_PENDING;
    }

    @ModelAttribute("AllUserStatus")
    public UserStatus[] createAllUserStatus() {
        return UserStatus.values();
    }



    @ModelAttribute("UserGender")
    public Gender createUserGender() {
        return Gender.UNKNOWN;
    }

    @ModelAttribute("AllUserGender")
    public Gender[] createAllUserGender() {
        return Gender.values();
    }

    @ModelAttribute("AllProvince")
    public List<Area> createAllArea() {
        return areaRepository.findAreaByParent(null);
    }

}
